package cn.wolfcode.trip.admin.controller;

import cn.wolfcode.trip.base.domain.Region;
import cn.wolfcode.trip.base.query.QueryObject;
import cn.wolfcode.trip.base.service.IRegionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/region")
public class RegionController {
    @Autowired
    private IRegionService regionService;

    @RequestMapping("/list")
    public String list(QueryObject qo, Model model) {
        return "region/list";
    }

    @RequestMapping("/listMenus")
    @ResponseBody
    public Object listMenus(Long parentId, String type) {
        //[{text:"xx", tags:"xx", id:xx}]
        List<Region> list = regionService.listMenus(parentId);
        /*//循环调用每一个Region对象的toTreeView方法,把返回的对象存入集合中一起转成JSON返回
        List<Map> views = new ArrayList<>();
        for (Region region : list) {
            views.add(region.toTreeView());
        }*/
        //通过参数type来决定,返回的格式
        if ("treeView".equals(type)) {
            //lambda表达式
            return list.stream().map(Region::toTreeView).collect(Collectors.toList());
        }
        return list;
    }

    @RequestMapping("/saveOrUpdate")
    public String saveOrUpdate(Region entity) {
        regionService.saveOrUpdate(entity);
        return "redirect:/region/list.do";
    }
}
